//
//  OrderHistoryView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import SwiftUI

struct OrderHistoryView: View {
    @EnvironmentObject var dataManager: DataManager
    @State private var selectedOrder: Order?
    @State private var showingOrderDetail = false
    
    var historyOrders: [Order] {
        dataManager.orders.filter { order in
            order.status == .completed || order.status == .cancelled
        }.sorted { $0.orderDate > $1.orderDate }
    }
    
    var body: some View {
        NavigationView {
            ZStack {
                // 深色背景
                LinearGradient(
                    colors: [
                        Color(red: 0.05, green: 0.05, blue: 0.05),
                        Color(red: 0.08, green: 0.08, blue: 0.08),
                        Color(red: 0.12, green: 0.10, blue: 0.09)
                    ],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
                
                VStack(spacing: 0) {
                    // 顶部导航
                    HStack {
                        Text(dataManager.currentLanguage == "zh" ? "订单历史" : "Order History")
                            .font(.title2)
                            .fontWeight(.bold)
                            .foregroundColor(.white)
                        
                        Spacer()
                    }
                    .padding(.horizontal, 20)
                    .padding(.top, 20)
                    .padding(.bottom, 15)
                    
                    // 订单列表
                    if historyOrders.isEmpty {
                        VStack(spacing: 20) {
                            Spacer()
                            
                            Image(systemName: "doc.text")
                                .font(.system(size: 60))
                                .foregroundColor(.gray)
                            
                            Text(dataManager.currentLanguage == "zh" ? "暂无订单历史" : "No Order History")
                                .font(.headline)
                                .foregroundColor(.gray)
                            
                            Text(dataManager.currentLanguage == "zh" ? "您还没有完成任何订单" : "You haven't completed any orders yet")
                                .font(.subheadline)
                                .foregroundColor(.gray.opacity(0.7))
                                .multilineTextAlignment(.center)
                            
                            Spacer()
                        }
                        .frame(maxWidth: .infinity)
                    } else {
                        ScrollView {
                            LazyVStack(spacing: 15) {
                                ForEach(historyOrders) { order in
                                    OrderHistoryRowView(
                                        order: order,
                                        onTap: {
                                            selectedOrder = order
                                            showingOrderDetail = true
                                        }
                                    )
                                }
                            }
                            .padding(.horizontal, 20)
                            .padding(.bottom, 100)
                        }
                    }
                }
            }
        }
        .navigationBarHidden(true)
        .sheet(isPresented: $showingOrderDetail) {
            if let order = selectedOrder {
                OrderDetailView(order: order)
            }
        }
    }
}

// MARK: - 订单历史行视图
struct OrderHistoryRowView: View {
    let order: Order
    let onTap: () -> Void
    @EnvironmentObject var dataManager: DataManager
    
    var body: some View {
        Button(action: onTap) {
            VStack(spacing: 15) {
                // 订单头部信息
                HStack {
                    VStack(alignment: .leading, spacing: 5) {
                        Text(order.orderNumber)
                            .font(.headline)
                            .fontWeight(.semibold)
                            .foregroundColor(.white)
                        
                        Text(formatDate(order.orderDate))
                            .font(.caption)
                            .foregroundColor(.gray)
                    }
                    
                    Spacer()
                    
                    VStack(alignment: .trailing, spacing: 5) {
                        OrderStatusBadge(status: order.status)
                        
                        Text("S$\(order.total, specifier: "%.2f")")
                            .font(.headline)
                            .fontWeight(.bold)
                            .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                    }
                }
                
                // 订单项目预览
                HStack {
                    VStack(alignment: .leading, spacing: 3) {
                        ForEach(Array(order.items.prefix(2)), id: \.id) { item in
                            Text("\(item.quantity)x \(dataManager.currentLanguage == "zh" ? item.menuItem.name : item.menuItem.englishName)")
                                .font(.subheadline)
                                .foregroundColor(.gray)
                                .lineLimit(1)
                        }
                        
                        if order.items.count > 2 {
                            Text(dataManager.currentLanguage == "zh" ? "等\(order.items.count)项" : "and \(order.items.count) items")
                                .font(.caption)
                                .foregroundColor(.gray.opacity(0.7))
                        }
                    }
                    
                    Spacer()
                    
                    // 重新订购按钮
                    if order.status == .completed {
                        Button(action: {
                            dataManager.reorderItems(from: order)
                        }) {
                            Text(dataManager.currentLanguage == "zh" ? "重新订购" : "Reorder")
                                .font(.caption)
                                .fontWeight(.medium)
                                .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                                .padding(.horizontal, 12)
                                .padding(.vertical, 6)
                                .background(
                                    RoundedRectangle(cornerRadius: 8)
                                        .stroke(Color(red: 1.0, green: 0.6, blue: 0.2), lineWidth: 1)
                                )
                        }
                        .onTapGesture {
                            dataManager.reorderItems(from: order)
                        }
                    }
                }
            }
            .padding(16)
            .background(
                RoundedRectangle(cornerRadius: 12)
                    .fill(Color(red: 0.15, green: 0.15, blue: 0.15))
                    .overlay(
                        RoundedRectangle(cornerRadius: 12)
                            .stroke(Color.gray.opacity(0.2), lineWidth: 1)
                    )
            )
        }
        .buttonStyle(PlainButtonStyle())
    }
    
    private func formatDate(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "MM/dd HH:mm"
        return formatter.string(from: date)
    }
}

#Preview {
    OrderHistoryView()
        .environmentObject(DataManager.shared)
}